const http = require('http')
const https = require('https')
const urllib = require('url')
const assert = require('assert')

function requestUrl (url, headers) {
    let urlOption = urllib.parse(url)
    let httpMode = null

    if (urlOption.protocol === 'http:') {
        httpMode = http
    } else if (urlOption.protocol === 'https:') {
        httpMode = https
    } else {
        throw new Error(`无法解析协议: ${urlOption.protocol}`)
    }

    return new Promise((resolve, reject) => {
        let req = httpMode.request({
            host: urlOption.host,
            path: urlOption.path,
            headers
        }, res => {
            if (res.statusCode >= 200 && res.statusCode < 300 || res.statusCode === 304) {
                let arr = []

                res.on('data', data => {
                    arr.push(data)
                })

                res.on('end', () => {
                    let buffer = Buffer.concat(arr)

                    resolve({
                        statusCode: res.statusCode,
                        body: buffer,
                        headers: res.headers
                    })
                })
            } else if (res.statusCode === 301 || res.statusCode === 302) {
                resolve({
                    statusCode: res.statusCode,
                    body: null,
                    headers: res.headers
                })
            } else {
                reject({
                    statusCode: res.statusCode,
                    body: null, 
                    headers: res.headers
                })
            }
        })

        req.on('error', error => {console.log(error)})
        req.write('')
        req.end()
    })
}

async function request (url, header) {
    try {
        while (1) {
            let { statusCode, body, headers } = requestUrl(url, header)

            if (statusCode === 200) {
                return { body, headers }
            } else {
                assert(statusCode === 301 || statusCode === 302)
                assert(headers.location)
                url = headers.location
            }
        }
    } catch (e) {
        console.log(e)
    }
}

module.exports = request
